package executor;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**手动模拟实现线程池
 * @author tongchen
 * @create 2023-01-20 18:45
 */
public class MyThreadPool {
   BlockingQueue<Runnable>runnables=new LinkedBlockingQueue<>();//阻塞队列
   //创建提交任务的方法
   public void submit(Runnable runnable) throws InterruptedException {
       runnables.put(runnable);
   }
   //创建取出任务的方法（构造方法）
    public MyThreadPool(int num){
       //检查num的合法性
        if(num<=0){
            throw new RuntimeException("输入的数字不合法");
        }
        //循环进行不断创建线程
        for(int i=0;i<num;++i){
             Thread thread =new Thread(()->{
                 while (true){
                     try {
                         Runnable take = runnables.take();
                         take.run();
                     } catch (InterruptedException e) {
                         throw new RuntimeException(e);
                     }
                 }

             });
             thread.start();
        }
    }
}
